//
//  ForgetPaypwdController.m
//  WaywardPoint_Code
//
//  Created by 韩盼盼 on 15/10/8.
//  Copyright (c) 2015年 易网新科技. All rights reserved.
//

#import "ForgetPaypwdController.h"
#import "ResetPaypwdController.h"

@interface ForgetPaypwdController ()<HeadBackView>
{
    UIButton *goBackBtn;
    UIButton *getUserPre;
    
    //验证页面
    UIView *VerifyView;
    NSTimer *_coolDownTimer;
    int _coolTime;
    int _stepTime;
    UIButton *againBtn;
    //    NSString *strtime;
    UITextField *userNo;
    UILabel *titleLab;
    UILabel *tishilabel;
    int starTime;
}

@property(nonatomic,strong)ResetPaypwdController *ResetPayVc;
@end

@implementation ForgetPaypwdController
-(ResetPaypwdController *)ResetPayVc
{
    if (!_ResetPayVc) {
        _ResetPayVc=[[ResetPaypwdController alloc]init];
    }
    return _ResetPayVc;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    HeadBackView *headview=[HeadBackView headbackView:@"填写验证码" andrightBtn:nil];
    headview.delegate=self;
    [self.view addSubview:headview];
    self.title = @"填写验证码";
    [self showUI];
}

- (void)showUI {
    UIView *contentView=[[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenW, ScreenH-20)];
    contentView.backgroundColor = COLOR_EVERYVIEWBG;
    
    [self.view addSubview:contentView];
    
    UILabel *titleLa1=[[UILabel alloc]initWithFrame:CGRectMake(15, 10, 80, 30)];
    titleLa1.text=@"验证码已发往";
    titleLa1.font=[UIFont systemFontOfSize:Font_SIZE_14-1];
    [contentView addSubview:titleLa1];
    titleLab=[[UILabel alloc]initWithFrame:CGRectMake(titleLa1.x+titleLa1.width+2, 5, 115, 35)];
    titleLa1.textColor = [UIColor grayColor];
    
    self.userIphone = [[NSUserDefaults standardUserDefaults] objectForKey:@"mobile"];
    titleLab.text=[NSString stringWithFormat:@"%@，",[self getNewString:self.userIphone]];

    titleLab.textAlignment=NSTextAlignmentLeft;
    titleLab.textColor = COLOR_TEXT_0;
    titleLab.font=[UIFont systemFontOfSize:Font_SIZE_14+2];
   
    [contentView addSubview:titleLab];
    UILabel *titleLa2=[[UILabel alloc]initWithFrame:CGRectMake(titleLab.x+titleLab.width+2, 10, 50, 30)];
    titleLa2.font=[UIFont systemFontOfSize:13];
    titleLa2.text=@"请稍后";
    [contentView addSubview:titleLa2];
    titleLa2.textColor = [UIColor grayColor];
    
    userNo=[[UITextField alloc]initWithFrame:CGRectMake(20, titleLab.y+40, contentView.width*0.5+20, 45)];
    userNo.backgroundColor=[UIColor whiteColor];
    userNo.placeholder=@"请输入验证码";
    userNo.tag=121;
    userNo.keyboardType=UIKeyboardTypeNumberPad;
    [userNo addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    userNo.userInteractionEnabled=YES;
    userNo.leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 45)];
    userNo.leftViewMode = UITextFieldViewModeAlways;
    
    againBtn=[[UIButton alloc]initWithFrame:CGRectMake(userNo.width+40, userNo.y, userNo.width*0.5-10, 45)];
    againBtn.titleLabel.font=[UIFont systemFontOfSize:17];
    [againBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    againBtn.backgroundColor = COLOR_BUTTON;
    [againBtn setTitle:@"发送" forState:UIControlStateNormal];
    againBtn.userInteractionEnabled = YES;
    [againBtn addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:againBtn];
    
    [contentView addSubview:userNo];

    tishilabel=[[UILabel alloc]initWithFrame:CGRectMake(20, userNo.y+55, userNo.width, 15)];
    tishilabel.hidden=YES;
    tishilabel.text=@"验证码错误";
    tishilabel.font=[UIFont boldSystemFontOfSize:13];
    tishilabel.textColor=RXDColor(223, 56, 109);
    [contentView addSubview:tishilabel];
    
    getUserPre=[[UIButton alloc]initWithFrame:CGRectMake(20, userNo.y+85, contentView.width-40, userNo.height)];
    [getUserPre setTitle:@"下一步" forState:UIControlStateNormal];
    [getUserPre addTarget:self action:@selector(verifynextstep) forControlEvents:UIControlEventTouchUpInside];
    [getUserPre setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    getUserPre.titleLabel.font=[UIFont boldSystemFontOfSize:18];
    getUserPre.backgroundColor = COLOR_UNBUTTON;
    getUserPre.userInteractionEnabled=NO;
    
    [contentView addSubview:getUserPre];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    userNo.text=@"";
    tishilabel.hidden=YES;
    getUserPre.backgroundColor = COLOR_UNBUTTON;
    getUserPre.userInteractionEnabled=NO;
    
//    [self startTime];
}

- (void)btnback
{
    [self.navigationController popViewControllerAnimated:YES];
    starTime=0;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    starTime=0;
}
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == userNo) {
        if (textField.text.length > 5) {
            textField.text = [textField.text substringToIndex:6];
            getUserPre.backgroundColor = COLOR_BUTTON;
            getUserPre.userInteractionEnabled=YES;
        }
        else
        {
            getUserPre.backgroundColor = COLOR_UNBUTTON;
            getUserPre.userInteractionEnabled=NO;
            tishilabel.hidden=YES;
            
        }
    }
}

- (void)verifynextstep
{
    if ([userNo.text isEqualToString:self.strRandomtext])
    {
        self.ResetPayVc.memberid=_memberid;
        self.ResetPayVc.payjumpStr=self.payjumpStr;
        self.ResetPayVc.captcha=_strRandomtext;
        [self.navigationController pushViewController:self.ResetPayVc animated:YES];
    }
    else
    {
        tishilabel.hidden=NO;
        tishilabel.text=@"验证码输入错误！";
    }

}

- (void)getCaptcha
{
    // 增加蒙板

    // 3.发送用户名和密码给服务器(走HTTP协议)
    // 创建一个URL ： 请求路径
    NSString *url = [NSString stringWithFormat:@"%@captcha",MRAPI];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    // 2.封装参数(这个字典只能放非文件参数)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"mobile"];
    params[@"type"]=[NSNumber numberWithInt:3];
    
    NSLog(@"captcha%@",params);
    
    [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *error=responseObject[@"error"];
        if (![error isEqualToString:@""]) {
            [MBProgressHUD showError:error];
        } else {
            self.strRandomtext=[NSString stringWithFormat:@"%@",responseObject[@"captcha"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark - 倒计时

- (void)startTime
{
    [self getCaptcha];
    
    starTime=60;
    //    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(starTime<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [againBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                againBtn.userInteractionEnabled = YES;
                againBtn.backgroundColor =  COLOR_BUTTON;
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"%.2d", starTime];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [againBtn setTitle:[NSString stringWithFormat:@"(%@)秒后\n重新发送",strTime] forState:UIControlStateNormal];
                againBtn.backgroundColor = COLOR_UNBUTTON;
                againBtn.titleLabel.numberOfLines=2;
                againBtn.userInteractionEnabled = NO;
                
            });
            starTime--;
        }
    });
    dispatch_resume(_timer);
}

/**字符串转换*/
- (NSString *)getNewString:(NSString *)temp
{
    NSMutableString *String1 = [[NSMutableString alloc] initWithString:temp];
    [String1 replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    return String1;
}
@end
